const fs = require('fs');
const { Order } = require('./Order');

function importOrdersFrom(name) {
    var readStream = fs.createReadStream('./' + name);
    let ordersStream = [];
    readStream.on('open', function (fd) {
        console.log('开始读取文件');
    });
    readStream.on('data', function (data) {
        ordersStream.push(data.toString());
    });
    readStream.on('end', function () {
        console.log('文件已全部读取完毕');
        const orders = JSON.parse(ordersStream.join(''));
        let index = 0;
        orders.forEach(o => {
            o.data.forEach(item => {
                if (!item.tag) return;
                Order.create({
                    orderDate: o.date,
                    tag: item.tag,
                    orderRef: item.comment.Ref || '',
                    cell: JSON.stringify(item.cell),
                    comment: item.comment.Ref ? '{}' : JSON.stringify(item.comment)
                });
            });
        })
    });
    readStream.on('close', function () {
        console.log('文件被关闭');
    });
    readStream.on('error', function (err) {
        console.log(err);

        console.log('读取文件失败');
    });

    async function saveOrder(o, item, hasRef) {
        if (hasRef) {
            await Order.create({
                orderDate: o.date,
                tag: item.tag,
                orderRef: item.comment.Ref,
                cell: JSON.stringify(item.cell),
                comment: JSON.stringify(item.comment)
            });
        } else {
            await Order.create({
                orderDate: o.date,
                tag: item.tag,
                orderRef: '',
                cell: JSON.stringify(item.cell),
                comment: JSON.stringify(item.comment)
            });
        }
    }
}

module.exports = {
    importOrdersFrom
}